# coding:utf-8
import web
import MySQLdb
import toJson

urls=(
      '/(top10\.do)', 'top10',
      '/(top10detail\.do)', 'top10detail',
      '/(.*)','index'
)
def getTops():
  conn=MySQLdb.connect(host="10.241.84.65",user="root",db="stock") 
  cursor = conn.cursor()
  sql = "select stock_class.des,stock_class.code,name,stock_info.curprice,stock_info.curwave from stock_class,stock_info where stock_class.code=stock_info.code;";
  cursor.execute(sql)
  alldata = cursor.fetchall()
  tops=dict()
  for i in alldata:
    print i[2] 
    pstr=""
    if i[4] < 0:
      pstr = "%.2f%%" % (i[4])
    else:
      pstr = "+%.2f%%" % (i[4])
    wstr = "%.2f" % (i[3])
    if i[0] not in tops:
      tops[i[0]] = list()
    tops[i[0]].append([i[1],i[2],wstr,pstr])
  resstr="{"
  for i in tops:
    resstr += "'%s':[" % (i)
    print i
    for j in tops[i]:
      tmpstr="["
      for k in j:
        tmpstr+="'%s',"%(k)
      tmpstr = tmpstr[:-1] + "],"
      resstr += tmpstr;
    resstr = resstr[:-1] + "],"
  resstr = resstr[:-1] + "}"
  return resstr

def getStockInfo(stocks):
  conn=MySQLdb.connect(host="10.241.84.65",user="root",db="stock")
  cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)  
  tmp = "("
  for i in stocks:
    tmp += "'"+i+"',"
  tmp = tmp[:-1] + ")"
  sql="select * from stock_info where code in %s" % (tmp)
  cursor.execute(sql)
  alldata=cursor.fetchall()
  #print type(alldata)
  return toJson.toJson(alldata)
getStockInfo(['600218','000807'])
#getTops()
app=web.application(urls,globals())
class index:
  def GET(self, name):
    return "index"

class top10:
  def GET(self, name):
    return getTops() 

class top10detail:
  def GET(self, name):
    #return web.input().topname
    conn=MySQLdb.connect(host="10.241.84.65",user="root",db="stock")
    conn.set_character_set('utf8')
    cursor = conn.cursor()
    tmp=web.input().topname
    #tmp.encode("UTF-8")
    sql="select code from stock_class where class='%s'" % (tmp)
    cursor.execute(sql) 
    alldata=cursor.fetchall()
    stocks=list()
    for i in alldata:
      stocks.append(i[0])
    return getStockInfo(stocks)
if __name__=='__main__':
  app.run()
